<?php

declare(strict_types=1);

namespace app\shop\controller\admin;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\controller\traits\Crud;
use app\shop\model\PayConfig as PayConfigModel;

/**
 * 支付配置
 */
class PayConfig extends Backend
{
    use Crud;

    public function initialize()
    {
        $this->model = new PayConfigModel;
    }


    /**
     * 支付配置列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $payConfigs = $this->model->sheepFilter()->paginate(request()->param('list_rows', 10));

        return success('获取成功', $payConfigs);
    }




    /**
     * 添加支付配置
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only([
            'name', 'type', 'params', 'status'
        ]);
        $this->svalidate($params, ".add");
        $this->svalidate($params['params'], '.' . $params['type']);     // 验证对应的支付参数是否设置完整

        Db::transaction(function () use ($params) {
            $this->model->save($params);
        });
        
        return success('保存成功');
    }


    /**
     * 支付配置详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $payConfig = $this->model->findOrFail($id);
        $payConfig->append(['params']);
        return success('获取成功', pay_config_show($payConfig));
    }



    /**
     * 修改支付配置
     *
     * @return \think\Response
     */
    public function edit($id)
    {
        $params = $this->request->only([
            'name', 'params', 'status'
        ]);
        $this->svalidate($params);

        $payConfig = $this->model->findOrFail($id);
        if (isset($params['params'])) {
            $this->svalidate($params['params'], '.' . $payConfig['type']);     // 验证对应的支付参数是否设置完整
        }

        Db::transaction(function () use ($payConfig, $params) {
            $payConfig->save($params);
        });
        return success('更新成功');
    }



    /**
     * 删除支付配置
     *
     * @param string $id 要删除的商品分类列表
     * @return void
     */
    public function delete($id)
    {
        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $payConfig) {
                $payConfig->delete();
            }
        });

        return success('删除成功');
    }


    /**
     * 获取所有支付配置
     *
     * @return \think\Response
     */
    public function select()
    {
        $payConfigs = $this->model->sheepFilter()->normal()
            ->field('id, name, type,status')
            ->select();

        return success('获取成功', $payConfigs);
    }
}
